package org.yang.common.core.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 异步任务配置
 *
 * @author: lslands
 * @version: 1.0
 * @create: 2024/5/19
 * @description:
 */
@Slf4j
@EnableAsync
@Configuration
public class AsyncConfig implements AsyncConfigurer {

    /**
     * 线程名字前缀
     */
    private static final String ASYNC_THREAD_PREFIX="asyncServiceExecutor -";
    /**
     * 核心线程池大小
     */
    private static final int CORE_POOL_SIZE=16;
    /**
     * 最大线程数
     */
    private static final int MAX_POOL_SIZE=20;
    /**
     * 活跃时间
     */
    private static final int KEEP_ALIVE_SECONDS=60;

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setThreadNamePrefix(ASYNC_THREAD_PREFIX);
        executor.setCorePoolSize(CORE_POOL_SIZE);
        executor.setMaxPoolSize(MAX_POOL_SIZE);
        // 配置队列容量，默认值为Integer.MAX_VALUE
        executor.setQueueCapacity(Integer.MAX_VALUE);
        executor.setKeepAliveSeconds(KEEP_ALIVE_SECONDS);
        // 设置此执行程序应该在关闭时阻止的最大秒数，以便在容器的其余部分继续关闭之前等待剩余的任务完成他们的执行
        executor.setAwaitTerminationSeconds(60);
        // 等待所有的任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 线程执行的拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        //返回可用处理器的Java虚拟机的数量 12
        log.info("当前可用处理器可用最大线程数量:{}",Runtime.getRuntime().availableProcessors());
        return executor;
    }
}
